const jwt = require('koa-jwt');
const {secret} = require('../config');
const Router = require('koa-router');
const router = new Router({prefix:'/user'});
const user_ctl = require('../controllers/users.js');

/**
 * 
 * @param {*} ctx 
 * @param {*} next 
 * 用户认证中间件,通过koa-jwt中间件实现;
 */
const auth = jwt({secret});

/**
 * 
 * @param {*} ctx 
 * @param {*} next 
 * 自己实现的jwt认证;
 */
// const auth = async (ctx,next) => {
//     try {
//     //获取客户端传过来的token信息;
//     //设置一个短路语法,若authorization没有值则为undefined,调用replace方法会报错;
//     const {authorization = ''} = ctx.request.header;
    
//     //验证token,注意'Bearer '一定要加空格!;
//     const token = authorization.replace('Bearer ', '');
    
//         //验证token;
//         const user = jwt.verify(token,secret);
//         //存放用户信息;
//         ctx.state.user = user;
//         console.log(JSON.stringify(ctx.state.user));
        
//     } catch (error) {
//         console.log('发生错误!');
//         ctx.throw(401,error.message);
//     }
//     await next();
// };

/**
     * 
     * @param {*} ctx 
     * @param {*下一个中间件} next 
     * 用户权限中间件;
*/
 const checkOwner = async (ctx,next)=>{
    if(ctx.params.id !== ctx.state.user._id){
        ctx.throw(403,'没有权限!');
    }
    await next();
}


router.post('/register',user_ctl.create);
router.post('/login',user_ctl.login);
router.delete('/:id',user_ctl.deleteById);
router.patch('/:id',auth,checkOwner,user_ctl.updateById);
router.get('/find',user_ctl.find);
router.get('/find/:id',user_ctl.findById);
router.get('/email/:email',user_ctl.isEmailExisted);
module.exports = router;
